const app = getApp();
//引入插件：微信同声传译
const plugin = requirePlugin('WechatSI');
//获取全局唯一的语音识别管理器recordRecoManager
const manager = plugin.getRecordRecognitionManager();

Page({
  data: {
    recordState: false,
    content: '',
    src: ''
  },
  onReady(e) {
    //创建内部 audio 上下文 InnerAudioContext 对象。
    this.innerAudioContext = wx.createInnerAudioContext();
    this.innerAudioContext.onError(function (res) {
      console.log(res);
      wx.showToast({
        title: '语音播放失败',
        icon: 'none',
      })
    }) 
  },
  onLoad: function (options) {
    this.initRecord();
  },

  initRecord: function () {
    const that = this;
    manager.onStart = function (res) {
      that.setData({
        recordState: true
      });
      console.log("成功开始录音识别", res)
    }
    manager.onError = function (res) {
      console.error("error msg", res)
    }
    manager.onStop = function (res) {
      that.setData({
        recordState: false
      });
      console.log('..............结束录音')
      console.log('录音临时文件地址 -->' + res.tempFilePath); 
      console.log('录音总时长 -->' + res.duration + 'ms'); 
      console.log('文件大小 --> ' + res.fileSize + 'B');
      console.log('语音内容 --> ' + res.result);
      if (res.result == '') {
        wx.showModal({
          title: '提示',
          content: '听不清楚,请重新说一遍!',
          showCancel: false
        })
        return;
      }
      var text = that.data.content + res.result;
      that.setData({
        content: text
      })
    }
  },

  touchStart: function (e) {
    manager.start({
      lang: 'zh_CN',
    })
  },

  touchEnd: function (e) {
    manager.stop();
  },

  conInput: function (e) {
    this.setData({
      content: e.detail.value,
    })
    console.log(e.detail.value);
  },

  wordYun: function (e) {
    var that = this;
    var content = this.data.content;
    plugin.textToSpeech({
      lang: "zh_CN",
      tts: true,
      content: content,
      success: function (res) {
        console.log("succ tts", res.filename);
        that.setData({
          src: res.filename
        })
        that.yuyinPlay();
      },
      fail: function (res) {
        console.log("fail tts", res)
      }
    })
  },

  yuyinPlay: function (e) {
    if (this.data.src == '') {
      console.log('暂无语音');
      return;
    }
    this.innerAudioContext = wx.createInnerAudioContext();
    this.innerAudioContext.src = this.data.src;
    this.innerAudioContext.play();
  },

  end: function (e) {
    if (this.innerAudioContext) {
      this.innerAudioContext.pause();
    }
  }
})